package com.spring.data.jpa.demo.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

public class Initializer implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext)
			throws ServletException {

		AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
		ctx.register(WebAppConfig.class);
		ctx.setServletContext(servletContext);

		// DispatcherServlet
		Dynamic servlet = servletContext.addServlet("springmvc",
				new DispatcherServlet(ctx));
		servlet.addMapping("*.do");
		servlet.setLoadOnStartup(1);

		// encodingFilter
		javax.servlet.FilterRegistration.Dynamic encodingFilter = servletContext
				.addFilter("encodingFilter", CharacterEncodingFilter.class);
		encodingFilter.setInitParameter("encoding", "UTF-8");
		encodingFilter.setInitParameter("forceEncoding", "true");
		// null 表示DispatcherType采用默认的DispatcherType.REQUEST
		encodingFilter.addMappingForUrlPatterns(null, true, "/*");
	}
}
